//
//  ContactViewController.m
//  BaseAPP
//
//  Created by Evisu on 16/12/18.
//  Copyright © 2016年 evisum. All rights reserved.
//

#import "ContactViewController.h"
#import "EMClient.h"

@interface ContactViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong)UITableView *tableView;

//好友列表
@property (nonatomic, strong)NSArray *userList;

@end

@implementation ContactViewController

- (void)viewDidLoad {

    [super viewDidLoad];
    
    [self initViews];
    [self layoutViews];
    
    
    
}

- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];
    
    //获取好友列表
    [self fetchContactsFromServer];
}

- (UITableView *)tableView {

    if (!_tableView) {
        
        _tableView = [[UITableView alloc] init];
    }
    
    return _tableView;
}

- (NSArray *)userList {

    if (!_userList) {
        
        _userList = [NSArray array];
    }
    
    return _userList;
}

- (void)initViews {

    [self showRightBarButtonWithImageName:@"barbuttonicon_addfriends"];
    self.rightBtnBlock = ^(){
        
        DMLog(@"add friend");
    };
    
    self.tableView = [[UITableView alloc] init];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    [self.view addSubview:self.tableView];
}

- (void)layoutViews {

    self.tableView.sd_layout
    .topSpaceToView(self.view, KSTATUS_AND_NAVIGATION_HEIGHT)
    .leftEqualToView(self.view)
    .rightEqualToView(self.view)
    .bottomSpaceToView(self.view, KTABBAR_HEIGHT);
}

#pragma mark - tableView dataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.userList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString *userStr = self.userList[indexPath.row];

    static NSString *reusedId = @"friend";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reusedId];
    
    if (!cell) {
        
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reusedId];
    }
    
    cell.textLabel.text = userStr;
    
    return cell;
    
}

#pragma mark 从服务器获取好友列表
- (void)fetchContactsFromServer {
    
    dispatch_async(KQUEUE_GLOBAL, ^{
        
        EMError *error = nil;
        NSArray *userlist = [[EMClient sharedClient].contactManager getContacts];
                
        dispatch_async(KQUEUE_MAIN, ^{
            
            if (!error) {
                
                self.userList = userlist;
                [self.tableView reloadData];
                
            } else {
                
                [MBProgressHUD showError:error.errorDescription toView:self.view];
            }
        });
    });
}

@end
